package com.iyao_app.manager;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.iyao_app.MyApplication;
import com.iyao_app.R;
import com.iyao_app.mvp.home.MainActivity;
import com.iyaowoqu.base_library.util.LogUtil;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/20.
 */

public class MessageManager {

    private static LinkedBlockingQueue<MessageVo> queue = new LinkedBlockingQueue<MessageVo>(100);
    private static RecyclerView mLayout;

    private static TranslateAnimation inAnim;//礼物View出现的动画
    private static TranslateAnimation outAnim;//礼物View消失的动画

    private final static int MESSAGE_PREPARE = 1;
    private final static int MESSAGE_ENTER = 2;
    private final static int MESSAGE_START = 0;


    private static Handler handler = new Handler(MyApplication.getInstance().getMainLooper()) {

        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {

                case MESSAGE_PREPARE:
                    final MessageVo messageVo = (MessageVo) msg.obj;
                    String userId = messageVo.getUserId();
                    Bitmap bitmap = messageVo.getBitmap();
                    String name = messageVo.getName();
                    String time = messageVo.getTime();
                    String location = messageVo.getLocation();
                    final View messageView;
                    //获取礼物的View的布局
                    messageView = LayoutInflater.from(cxt.get()).inflate(R.layout.item_message, null);
                    messageView.setTag(userId);
                    LinearLayout lin_root = messageView.findViewById(R.id.lin_root);
                    CircleImageView cover_head = messageView.findViewById(R.id.cover_head);
                    TextView tv_name = messageView.findViewById(R.id.tv_name);
                    TextView tv_location = messageView.findViewById(R.id.tv_location);
                    TextView tv_time = messageView.findViewById(R.id.tv_time);
                    float dimension = cxt.get().getResources().getDimension(R.dimen.x100);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) dimension);
                    lp.topMargin = 10;
                    messageView.setLayoutParams(lp);
                    cover_head.setImageBitmap(bitmap);
                    tv_name.setText(name);
                    tv_time.setText("1小时前");
                    tv_location.setText(location);
                    mLayout.addView(messageView);

                    inAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 1);
                    inAnim.setDuration(2000);
                    outAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 1);
                    outAnim.setDuration(2000);
                    messageView.startAnimation(inAnim);//播放礼物View出现的动
                    inAnim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            messageView.startAnimation(outAnim);//播放礼物View出现的动
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    outAnim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {

                            int position = messageVo.getPosition();
                            map.put(position, false);
                            count--;
                            mLayout.removeView(messageView);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });

                    break;

                case MESSAGE_START:
                    if (queue != null && queue.size() > 0) {
                        if (mLayout.getVisibility() == View.GONE)
                            mLayout.setVisibility(View.VISIBLE);
                        if (mLayout.getChildCount() == 2) {

                        } else {
                            final MessageVo poll = queue.poll();
                            if (poll != null) {//如果从队列中获取的礼物不为空，那么就将礼物展示在界面上
                                Glide.with(cxt.get()).load(poll.getImage()).asBitmap().into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                        poll.setBitmap(resource);
                                        Message message = handler.obtainMessage();
                                        message.what = MESSAGE_ENTER;
                                        message.obj = poll;
                                        handler.sendMessage(message);
                                    }
                                }); //方法中设置asBitmap可以设置回调类型
                            }
                        }
                    } else {
                        mLayout.removeAllViews();
                        mLayout.setVisibility(View.GONE);
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private static WeakReference<MainActivity> cxt = null;
    private static int count = 0;
    private Subscription mSubscription;
    private static Map<Integer, Boolean> map = new HashMap<>();

    public MessageManager(MainActivity cxt, final RecyclerView layout) {
        this.cxt = new WeakReference<MainActivity>(cxt);
        //对Activity的弱引用
        this.mLayout = layout;

        map.put(1, false);
        map.put(2, false);
        map.put(3, false);
        Flowable.interval(1, TimeUnit.SECONDS)
                .onBackpressureDrop()  //加上背压策略
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        mSubscription = s;
                        s.request(Long.MAX_VALUE);
                    }

                    @Override
                    public void onNext(Object aLong) {
                        if (queue.size() > 0) {
                            for (Boolean aBoolean : map.values()) {
                                if (aBoolean) {
                                    count++;
                                }
                            }
                            if (count < 3) {
                                LogUtil.e("==" + queue.size());
                                MessageVo poll = queue.poll();
                                Message message = handler.obtainMessage();
                                message.what = MESSAGE_PREPARE;
                                message.obj = poll;
                                if (!map.get(1)) {
                                    map.put(1, true);
                                    poll.setPosition(1);
                                } else if (!map.get(2)) {
                                    map.put(2, true);
                                    poll.setPosition(2);
                                } else if (!map.get(3)) {
                                    map.put(3, true);
                                    poll.setPosition(3);
                                }
                                handler.sendMessage(message);

                            }

                        }
//
                    }

                    @Override
                    public void onError(Throwable t) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    public void addMessage(MessageVo vo) {
        queue.offer(vo);
    }

}
